package com.onetech.adrewards.free.models;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import org.json.JSONArray;
import org.json.JSONObject;

import android.os.Bundle;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.onetech.adrewards.free.OneTech_ApplicationContext;
import com.onetech.adrewards.free.config.AppConfig.Cache;
import com.onetech.adrewards.free.http.APIRequestResult;
import com.onetech.adrewards.free.http.ZuZuHttpRequest;
import com.onetech.adrewards.free.listener.AdRewardIF;
import com.onetech.adrewards.free.objects.AdDTO2;
import com.onetech.adrewards.free.utils.AdrewadsUtils;
import com.zuzu.db.store.SimpleStoreIF;

public class AdRewardModel implements AdRewardIF {
	private static AdRewardIF _instance;
	private static final Lock createLock = new ReentrantLock();
	private static final int STORE_EXPIRE = 5 * 60;

	public AdRewardModel() {
		getStoreAdapter();
	}

	public static AdRewardIF getInstance() {
		if (_instance == null) {
			createLock.lock();
			if (_instance == null) {
				_instance = new AdRewardModel();
			}
			createLock.unlock();
		}
		return _instance;
	}

	private SimpleStoreIF getStoreAdapter() {
		return AdrewadsUtils.getStoreAdapter(Cache.ADREWARD_NAME,
				OneTech_ApplicationContext.getContext(), Cache.ADREWARD_NUMBER);
	}

	public void setStore(String key, Object item) {
		if (item == null) {
			return;
		}
		Gson gson = new Gson();
		String temp = gson.toJson(item);
		this.getStoreAdapter().put(key, temp, STORE_EXPIRE);
	}

	@Override
	public List<AdDTO2> getListAds(String url,String type,String page,String sortType){
		try {
			List<AdDTO2> result=new ArrayList<AdDTO2>();
			String key=Cache.ADREWARD_PAGE_KEY+type+page+String.valueOf(sortType);
			String json=getStoreAdapter().get(key);
			result=deserializeListAds(json);
			if(result!=null){
				return result;
			}
			AdrewadsUtils.checkUId();
			Bundle mBundle=new Bundle();
			APIRequestResult data = ZuZuHttpRequest.getInstance().getDataFromServer(url, mBundle);
			if (data == null) {
				return null;
			}
			result=parserListAds(data);
			if(result!=null && result.size()>0){
				setStore(key, result);
			}
			return result;
		} catch (Exception e) {
			return null;
		}
	}
	private List<AdDTO2> parserListAds(APIRequestResult data){
		List<AdDTO2> result=null;
		try {			
			if (data.error_code.equals("0") && data.data != null && !data.data.equals("")) {
				JSONObject jb=(JSONObject)data.data;
				JSONArray jArr=jb.getJSONArray("result");
				if(jArr!=null && jArr.length()>0){
					result=new ArrayList<AdDTO2>();
					for (int i = 0; i < jArr.length(); i++) {
						JSONObject temp=jArr.getJSONObject(i);
						AdDTO2 ad=deserialize2AdDTO(temp);
						if(ad!=null){
							result.add(ad);
						}
					}
				}
			}
		} catch (Exception e) {
		}
		return result;
	}
	private AdDTO2 deserialize2AdDTO(JSONObject jb){
		try {
			AdDTO2 result=new AdDTO2();
			result.att=jb.optString("attribute");
			result.btn_text=jb.optString("btn_text");
			result.coin=jb.optString("coin");
			result.img=jb.optString("img");
			result.id=jb.optString("id");
			result.is_app=jb.optString("is_app");
			result.is_max=jb.optString("is_max");
			result.is_video=jb.optString("is_video");
			result.name=jb.optString("name");
			result.remark=jb.optString("remark");
			result.sale_coin=jb.optString("sale_coin");
			
			result.short_desc=jb.optString("short_desc");
			result.source=jb.optString("source");
			result.url=jb.optString("url");
			result.charge_type=jb.optString("charge_type");
			result.wait_time=jb.optString("wait_time");
			
			result.is_rank=jb.optString("is_rank");
			result.is_rec=jb.optString("is_rec");
			result.start_date=jb.optString("start_date");
			result.charge_cate=jb.optString("charge_cate");
			result.rec_cate=jb.optString("rec_cate");
			result.camp_cate=jb.optString("camp_cate");
			result.icon_mark=jb.optString("icon_mark");
			result.rec_text=jb.optString("rec_text");
			return result;
		} catch (Exception e) {
			return null;
		}
	}
	@SuppressWarnings("unchecked")
	private List<AdDTO2> deserializeListAds(String json) {
		List<AdDTO2> result = null;
		if (json == null || json.equals(""))
			return result;
		try {
			result = new ArrayList<AdDTO2>();
			Gson gson = new Gson();
			Type listType = new TypeToken<List<AdDTO2>>() {
			}.getType();
			result = (List<AdDTO2>) gson.fromJson(json, listType);
		} catch (Exception e) {
			return null;
		}
		return result;
	}
	
	@Override
	public void clearAllData() {
		this.getStoreAdapter().removeAll();		
	}
}
